package com.sinog.biz.schedule;

import com.sinog.biz.BizApplication;
import com.sinog.biz.mapper.havexml.other.DsSqlMapper;
import com.sinog.biz.util.CodeUrlUtils;
import com.sinog.core.utilbean.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @desc 定时清洗数据的类
 * @author ybl
 * @date 2022/9/26
 */
@Slf4j
@Component
@Configuration
@ConditionalOnProperty(name = "gkzx.azbj.timingClear.open", havingValue = "true")
public class DataCleanSchedule {

    /**
     * 部级资源库
     */
    private JdbcTemplate bujiJdbcTemplate;
    @Resource
    private DsSqlMapper dsSqlMapper;

    /**
     * 定时执行数据库清洗方法
     */
    @Scheduled(cron = "${gkzx.azbj.timingClear.cron}")
    public void dataClean() {
        // 数据源
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        String sql = "select * from ds_sql ds where ds.`type` not in ('0') and (ds.carry_result not like ('%" + CodeUrlUtils.getLocalCodeStartTwo() + "%') or ds.carry_result is null) and (ds.province = -1 or ds.province like ('%" + CodeUrlUtils.getLocalCodeStartTwo() + "%'))";
        List<Map<String,Object>> sqlList = bujiJdbcTemplate.queryForList(sql);
        // 声明四大类型
        List<Map<String,Object>> addList = new ArrayList<>(16);
        List<Map<String,Object>> delList = new ArrayList<>(16);
        List<Map<String,Object>> updateList = new ArrayList<>(16);
        //分别执行
        for(Map<String,Object> item : sqlList) {
            if(Constants.NumberStr.NUM_STR_ONE.equals(item.get("sql_type"))) {
                addList.add(item);
            } else if(Constants.NumberStr.NUM_STR_TWO.equals(item.get("sql_type"))) {
                delList.add(item);
            } else if(Constants.NumberStr.NUM_STR_THREE.equals(item.get("sql_type"))) {
                updateList.add(item);
            }
        }
        //执行添加操作，顺序执行，避免锁表
        if(addList.size() != 0) {
            executeTask(addList,1);
        }
        //执行删除操作
        if(delList.size() != 0) {
            executeTask(delList,2);
        }
        //执行修改操作
        if(updateList.size() != 0) {
            executeTask(updateList,3);
        }
    }

    /**
     * 执行任务
     * @param list 需要执行的内容
     * @param type 执行列别，增删改123
     */
    private void executeTask(List<Map<String,Object>> list,int type) {
        for(Map<String,Object> item : list) {
            try {
                switch(type) {
                    case 1:
                        dsSqlMapper.addSqlList((String)item.get("content"));
                        break;
                    case 2:
                        dsSqlMapper.delSqlList((String)item.get("content"));
                        break;
                    case 3:
                        dsSqlMapper.updateSqlList((String)item.get("content"));
                        break;
                    default:
                        break;
                }
            } catch(Exception e) {
                log.error(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>定时执行sql发生错误，错误省份：{}，错误语句语句：{}",CodeUrlUtils.getLocalCodeStartTwo(),item.get("content"));
                updateDsSqlType((Integer)item.get("id"),3);
                continue;
            }
            updateDsSqlType((Integer)item.get("id"),2);
            log.info("定时执行sql任务：" + item.get("remark") + "=》" + item.get("content"));
        }
    }

    /**
     * 修改定时sql的完成状态
     * @param id 要修改的id
     * @param type 修改的状态，2.已完成，3.失败
     */
    private void updateDsSqlType(Integer id,int type) {
        ApplicationContext applicationContext = BizApplication.applicationContext;
        bujiJdbcTemplate = (JdbcTemplate)applicationContext.getBean("bujiJdbcTemplate");
        String sql;
        if(type==2){
            sql = "update ds_sql set type = " + type + " , carry_result = CONCAT(IFNULL(carry_result,''),'" + CodeUrlUtils.getLocalCodeStartTwo() + ",') where id = " + id;
        }else {
            sql = "update ds_sql set type = '" + type + "' where id = " + id;
        }
        bujiJdbcTemplate.update(sql);
    }
}